package controllers

import (
	"github.com/astaxie/beego"
	"beeblog/models"
	"strings"
)

type TopicController struct {
	beego.Controller
}

func (this *TopicController) Get()  {
	 this.Data["IsLogin"] = checkAccount(this.Ctx)
	 this.Data["IsTopic"] = true
     this.TplName = "topic.html"
     topics,err := models.GetAllTopics("",false)
     if err != nil{
     	beego.Error(err)
	 }else {
	 	this.Data["Topice"] = topics
	 }
}

func (this *TopicController) Post() {
	/*if !checkAccount(this.Ctx){
		this.Redirect("/login",302)
		return
	}*/
	title := this.Input().Get("title")
	content := this.Input().Get("content")
    tid := this.Input().Get("tid")
    category := this.Input().Get("category")
    lable := this.Input().Get("lable")

	var err error
	//根据tid判断是新增文章还是修改文章
	if len(tid) == 0{
		err = models.AddTopic(title,content,category,lable)
	}else {
		err = models.ModifyTopic(tid,title,content,category,lable)
	}

	if err != nil{
		beego.Error(err)
	}

	this.Redirect("/topic",301)
}

func (this *TopicController) Add()  {
	this.TplName = "topic_add.html"
	//this.Ctx.WriteString("add")
}

func (this *TopicController) View()  {
	this.TplName="topic_views.html"

	//key代表url后的参数
	//localhost:8080/view/0(参数)/1(参数)...
	topic,err := models.GetTopic(this.Ctx.Input.Param("0"))
	if err != nil {
		beego.Error(err)
		this.Redirect("/",301)
		return
	}

	this.Data["Topic"] = topic
	this.Data["Lables"] = strings.Split(topic.Labels," ")
	this.Data["Tid"] = this.Ctx.Input.Param("0")

	tid := this.Ctx.Input.Param("0")
	replay,err := models.QueryReplay(tid)
	if err != nil{
		beego.Error(err)
		return
	}

	this.Data["Replay"] = replay
}

/**
   修改
 */
func (this *TopicController) Modify()  {
	this.TplName ="topic_modify.html"

	tid := this.Input().Get("tid")
	topic,err := models.GetTopic(tid)
	if err != nil{
		beego.Error(err)
		this.Redirect("/",301)
		return
	}

	this.Data["Topic"] = topic
	this.Data["Tid"] = tid
}

/**
删除
 */
func (this *TopicController) Delete()  {
	//this.TplName ="topic.html"
	/*tid := this.Input().Get("tid")
	err := models.DeleteTopic(tid)*/

	tid := this.Ctx.Input.Param("0")
	err := models.DeleteTopic(tid)
	if err != nil{
		beego.Error(err)
	}

	this.Redirect("/topic",301)
}
